<?php
/**
 * 邮件模型
 * @author cjli
 *
 */
class EmailModel
{
    public $_mail;
    private $_var;

    /**
     * 构造邮件数据初始化
     * @param array $cfg 邮件配置参数
     */
    public function __construct($cfg)
    {
        if(empty($cfg) || !is_array($cfg)) {
            $cfg = array(
                'mail_type' => C('mail_type'),
                'mail_auth' => C('mail_auth'),
                'mail_ssl' => C('mail_ssl'),
                'mail_server' => C('mail_server'),
                'mail_port' => C('mail_port'),
                'mail_user' => C('mail_user'),
                'mail_password' => C('mail_password'),
                'mail_from' => C('mail_from'),
            );
        }
        require_once LIBRARY_PATH.'COM/class.phpmailer.php';
        $this->_mail = new PHPMailer();
        $cfg['mail_type'] ? $this->_mail->IsSMTP() : $this->_mail->IsMail();
        $this->_mail->CharSet = "utf-8";
        $this->_mail->SMTPAuth = true;
        if(isset($cfg['mail_ssl']) && $cfg['mail_ssl']){
            $this->_mail->SMTPSecure = "ssl";
        }
        $this->_mail->Host = $cfg['mail_server'];
        $this->_mail->Port = $cfg['mail_port'];
        $this->_mail->Username = $cfg['mail_user'];
        $this->_mail->Password = $cfg['mail_password'];
        $this->_mail->SMTPDebug = false;

        $this->_var->mailfrom = $cfg['mail_from'];
        $this->_var->mailfromname = $cfg['mail_user'];
        $this->_var->mailreply = $cfg['mail_from'];
        $this->_var->mailreplyname = $cfg['mail_user'];
    }

    /**
     *
     * 发送邮件方法
     * @param string $address 发送邮件地址，多个用,隔开
     * @param string $subject 邮件标题
     * @param string $content 邮件内容
     */
    public function sendMail($address, $subject, $content, $ishtml = 'html' , $username = '')
    {
        /*
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/home/sendMail';
        $senddata = array(
            'email'     => $address,
            'title'     => $subject,
            'content'   => $content,
            'ishtml'    => $ishtml,
            'username'  => $username,
        );
        Log::write('send_1 log:'.json_encode($senddata));
        $headers = "From:<mail@ownonly.cn>\n";
        $headers .= "Return-Path: <".$address.">\n";	 //防止被当做垃圾邮件，但在sina邮箱里不起作用
        $headers .= "MIME-Version: 1.0\n";
        $headers .= "Content-type: text/html; charset=utf-8\n";    //邮件内容为utf-8编码
        $headers .= "Content-Transfer-Encoding: 8bit\r\n";	 //注意header的结尾，只有这个后面有\r
        ini_set('sendmail_from', 'mail@ownonly.cn');
        $re_mail = mail($address, $subject, $content,$headers);
        return $re_mail;
        //$this->Asynchronous_request($url, array('senddata'=>base64_encode(json_encode($senddata))) , 'post');
        */
        $isBcc = false;
        $this->_mail->SetFrom($this->_var->mailfrom, $this->_var->mailfromname);
        $this->_mail->AddReplyTo($this->_var->mailreply, $this->_var->mailreplyname);
        $this->_mail->Subject = $subject;
        if ($ishtml == 'html') {
            $this->_mail->MsgHTML($content);
        } else {
            $this->_mail->Body = $content;
        }
        $this->_mail->ClearAddresses();
        $this->_mail->ClearBCCs();
        if (is_array($address)) {
            if (isset($address[0]))
                $this->_mail->AddAddress($address[0], $username);
            if (isset($address[1]))
                $this->_mail->AddBCC($address[1], $username);
        } else {
            $this->_mail->AddAddress($address, $username);
        }
        if($isBcc){
            $this->_mail->AddBCC('invoices@3ecxt0t2x9.referralcandy.com');
            $username = '';
        }
        if(!$this->_mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     *
     * 发送邮件方法
     * @param string $address 发送邮件地址，多个用,隔开
     * @param string $subject 邮件标题
     * @param string $content 邮件内容
     */
    public function sendMail_direct($address, $subject, $content, $ishtml = 'html' , $username = '')
    {
        //取消订阅地址
        $unsubscribe_url = MeasureModel::unsubscribe_url($address);
        $content = str_replace('{$unsubscribe_url}', $unsubscribe_url, $content);
        $isBcc = false;
        if($username == 'bcc'){
            $username = '';$isBcc = true;
        }

        $this->_mail->SetFrom($this->_var->mailfrom, $this->_var->mailfromname);
        $this->_mail->AddReplyTo($this->_var->mailreply, $this->_var->mailreplyname);
        $this->_mail->Subject = $subject;
        if ($ishtml == 'html') {
            $this->_mail->MsgHTML($content);
        } else {
            $this->_mail->Body = $content;
        }
        $this->_mail->ClearAddresses();
        $this->_mail->ClearBCCs();
        if (is_array($address)) {
            if (isset($address[0]))
                $this->_mail->AddAddress($address[0], $username);
            if (isset($address[1]))
                $this->_mail->AddBCC($address[1], $username);
        } else {
            $this->_mail->AddAddress($address, $username);
        }
        if($isBcc){
            $this->_mail->AddBCC('invoices@3ecxt0t2x9.referralcandy.com');
            $username = '';
        }
        if(!$this->_mail->Send()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 邮件替换
     * @param string $content 替换内容
     * @param array $orderInfo 订单信息
     */
    public function replaceMail($content, $orderInfo = null)
    {
        global $user;
        if($orderInfo){
            $user_name = $orderInfo['delivery_first_name'] .'.'. $orderInfo['delivery_last_name'];
        }elseif($user['id']){
            $userInfo = UserModel::get_user_info($user['id']);
            $user_name = $userInfo['user_name'];
        }else{
            $user_name = 'customer';
        }
        $sitetokens = array('site_name', 'site_url', 'site_email');

        $ordertokens = array('order_sn','pay_amount','delivery_first_name','delivery_last_name','delivery_email',
            'delivery_phone','delivery_mobile','delivery_country','delivery_province','delivery_city',
            'delivery_address','delivery_address2','delivery_address3','delivery_postcode','delivery_time','payment_method','shipping_method',
            'shipping_time','create_time','shipping_no','surplus_money',
        );

        $content = str_replace('{$time}', date('d-m-Y H:i:s', time()), $content);

        $content = str_replace('{$user_name}', $user_name, $content);

        foreach ($sitetokens as $v) {
            if($v =='site_url'){
                $siteurl = str_replace('http://', '', C('site_url'));
                $siteurl = 'http://' .trim($siteurl, '/');
                $content = str_replace('{$site_url}', $siteurl, $content);
            }elseif($v == 'site_name'){
                $content = str_replace('{$site_name}', C('site_name'), $content);
            }elseif($v == 'site_email'){
                $content = str_replace('{$site_email}', C('site_email'), $content);
            }
        }
        if($orderInfo){
            //发货通知邮件中的预计收到时间
            $predict_starttime = 4;
            $predict_endtime = 7;
            if('shipping_id' == '11'){
                $predict_starttime = 1;
                $predict_endtime = 3;
            }
            $content = str_replace('{$predict_starttime}', date('l,F d, Y',time()+$predict_starttime*86400), $content);
            $content = str_replace('{$predict_endtime}', date('l,F d, Y',time()+$predict_endtime*86400), $content);
            //订单详情地址URL
            $webUrl = 'http://'.$_SERVER['HTTP_HOST'];
            if($orderInfo['user_id']>0){
                $order_detail_url = '/user/order_info?oid='.$orderInfo['id'];
            }else{
                $order_detail_url = '/order/query?order_sn='.$orderInfo['order_sn'];
            }
            $content = str_replace('{$order_detail_url}',$webUrl.$order_detail_url, $content);

            foreach ($ordertokens as $v) {
                if($v == 'shipping_time'){
                    $orderInfo[$v] = date('d-m-Y H:i:s', $orderInfo['shipping_time']);
                }elseif($v=='create_time'){
                    $orderInfo[$v] = date('d-m-Y H:i:s', $orderInfo['start_time']);
                }
                if($v == 'payment_method' && $orderInfo['pay_amount'] == 0){
                    $orderInfo[$v] = L('use_balance_to_pay');
                }
                if($v == 'pay_amount'){
                    if($orderInfo['pay_amount'] > 0){
                        $curr_pay_amount = currency($orderInfo['pay_amount']);
                    }else{
                        $curr_pay_amount = currency($orderInfo['surplus_money']);
                    }
                    $content = str_replace('{$order.pay_amount}', $curr_pay_amount, $content);
                    continue;
                }
                $content = str_replace('{$order.' . $v . '}', $orderInfo[$v], $content);
            }

            //全部一次性的
            if (isset($orderInfo) && isset($orderInfo['productList'])) {
                $str = '';
                if(is_array($orderInfo['productList'])) foreach ($orderInfo['productList'] as $product) {
                    $str .= '<tr><td><a href="' . url('product/info', 'id='.$product['product_id']) . '"><img border="0" src="'. url($product['small_img']) . '"/></a></td><td>' . $product['name'] . '<br/>';
                    $str .=  '</td><td>' . (isset($product['pay_price']) ? currency($product['pay_price']) : null) . '</td><td>' . $product['qty'] . '</td><td>' . (isset($product['total_amount']) ? currency($product['total_amount']) : null) . '</td></tr>';
                }
                $str .= '<tr><td colspan="4" style="text-align: right;">Total Amount:</td><td>' . (isset($orderInfo['product_amount']) ? currency($orderInfo['product_amount']) : null) . '</td></tr>';
                $str .= '<tr><td colspan="4" style="text-align: right;">Shipping Fee:</td><td>' . (isset($orderInfo['shipping_fee']) ? currency($orderInfo['shipping_fee']) : null) . '</td></tr>';
                //$str .= '<tr><td colspan="4" style="text-align: right;">payment fee:</td><td>' . (isset($orderInfo['payment_fee']) ? currency($orderInfo['payment_fee']) : null) . '</td></tr>';
                if($orderInfo['surplus_money']){
                    $str .= '<tr><td colspan="4" style="text-align: right;">Use Credit:</td><td>-' . (isset($orderInfo['surplus_money']) ? currency($orderInfo['surplus_money']) : null) . '</td></tr>';
                }
                if($orderInfo['coupon_money'] || $orderInfo['hongbao_money']){
                    $str .= '<tr><td colspan="4" style="text-align: right;">You Save:</td><td>-' . currency($orderInfo['hongbao_money']+$orderInfo['coupon_money']) . '</td></tr>';
                }
                $str .= '<tr><td colspan="4" style="text-align: right;">Pay Amount:</td><td>' .(isset($orderInfo['pay_amount']) ? currency($orderInfo['pay_amount']) : null) . '</td></tr>';
                //$str .= '</table>';
                $content = str_replace('{$order.productList}', $str, $content);
            }
            //分单产品列表
            elseif (isset($orderInfo) && isset($orderInfo['deliveryList'])) {
                $str = '<table width="90%">';
                $str .= '<tr><td>Image</td><td>Product name</td><td>Price</td><td>Quantity</td><td>Send Number</td><td>Sub-Total</td></tr>';
                $total_amount=0;
                if(is_array($orderInfo['deliveryList'])) foreach ($orderInfo['deliveryList'] as $product) {
                    $total_amount += $product['pay_price']*$product['send_number'];
                    $str .= '<tr><td><a href="' . url('product/info', 'id='.$product['product_id']) . '"><img border="0" src="' . url($product['small_img']) . '"/></a></td><td>' . $product['product_name'] . '<br/>';
                    if (isset($product['attr']) && $product['attr'] != '') {
                        $str .= $product['attr'];
                    }
                    $str .=  '</td><td>' . (isset($product['pay_price']) ? currency($product['pay_price']) : null) . '</td><td>' . $product['qty'] . '</td><td>' . $product['send_number'] . '</td><td>' . currency($product['pay_price']*$product['send_number']) . '</td></tr>';
                }
                $str .= '<tr><td colspan="3"></td><td colspan="2">product total amount:' .(isset($total_amount) ? currency($total_amount) : null) . '</td></tr>';
                $str .= '</table>';
                $content = str_replace('{$order.productList}', $str, $content);
            }
        }
        return $content;
    }



    public function Asynchronous_request($url,$data,$method='post'){//异步发送邮件测试
        //拆解url
        $url = str_replace("http://","",$url);
        @$posi = strpos($url,'/',$start);
        @$uri = substr($url,$posi);
        @$host = substr($url,0,$posi);
        $content = '';
        while (list($k,$v) = each($data)) {
            $content .= rawurlencode($k)."=".rawurlencode($v)."&";
        }
        $result = self::http_post($host,$uri,$content);
        return $result;
    }

    private  function http_post($host,$url,$params,$timeout=15)
    {
        $result="";
        //创建socket连接
        $fp = fsockopen($host,80,$errno,$errstr,$timeout);

        if (!$fp)
        {
            $result = $errstr."--->".$errno;
            return $result;
        }

        $length = strlen($params);
        //构造post请求的头
        $header = "POST ".$url." HTTP/1.1\r\n";
        $header .= "Host:".$host."\r\n";
        $header .= "Referer:/qianxiang/post.php\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".$length."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        //添加post的字符串
        $header .= $params."\r\n";
        //发送post的数据
        fputs($fp,$header);

        fclose($fp);
        return TRUE;
    }

}